package com.example.healthcode2;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;

import java.util.HashMap;
import java.util.Map;
//注册页面Activity
public class registerActivity extends AppCompatActivity {
    private EditText editText_name, editText_paw, editText_paw2;
    private ImageView imageView;
    private Button button_zhuce;
    private Dialog dialogLoading;


    private final static int ZHECE_OK = 4;
    private final static int ZHECE_NO = 5;
    private final static int ZHECE_ERROR = 6;
    private final static int OTHER=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        editText_name = findViewById(R.id.register_text_name);
        editText_paw = findViewById(R.id.register_text_password);
        editText_paw2 = findViewById(R.id.register_text_password2);
        imageView = findViewById(R.id.register_img_fanhui);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        button_zhuce = findViewById(R.id.register_btn_zhuce);

    }

//注册按钮
    public void registerClick(View view) {
        final String name = editText_name.getText().toString();
        final String paw = editText_paw.getText().toString();
        String paw2 = editText_paw2.getText().toString();

        if (name.isEmpty() || paw.isEmpty() || paw2.isEmpty()) {
            dialogshow("注册失败", "请输入要注册的用户名和密码");
            return;
        }
        if (!(paw.equals(paw2))) {
            dialogshow("注册失败", "两次密码输入不一致");
            return;
        }


        button_zhuce.setEnabled(false);//让按钮失效
        final RequestQueue queue = Volley.newRequestQueue(this);
        String url = "http://30r97104b2.qicp.vip/user/register";
        final StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        if ("success".equals(s)) {
                            myHandler.sendEmptyMessage(ZHECE_OK);
                        } else if("error".equals(s)) {
                            myHandler.sendEmptyMessage(ZHECE_NO);
                        }else {
                            myHandler.sendEmptyMessage(OTHER);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        myHandler.sendEmptyMessage(ZHECE_ERROR);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", name);
                params.put("password", paw);
                return params;
            }
        };

        dialogLoadingshow();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);//延时发送
                    queue.add(request);//发送请求
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
//加载对话框
    private void dialogLoadingshow() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_loading, null);
        dialogLoading = new AlertDialog.Builder(this, R.style.LoadingDialog).setView(view).create();
        ImageView imageView = view.findViewById(R.id.dialog_img_loading);
        TextView textView = view.findViewById(R.id.dialog_text_loading);
        textView.setText("注册中...");
        Glide.with(this).load(R.drawable.load_0_gif).into(imageView);
        dialogLoading.show();
        Window window = dialogLoading.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.9 * screenWidth);
        params.y = (int) (0.05 * screenHeight);
        window.setAttributes(params);
        window.setGravity(Gravity.TOP);
    }

    //弹出对话框
    private void dialogshow(String a, String s) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_sign, null);
        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.MyDialog).setView(view).create();
        TextView textView = view.findViewById(R.id.dialog_text_sign1);
        TextView textView1 = view.findViewById(R.id.dialog_text_sign0);
        textView1.setText(a);
        textView.setText(s);
        Button button = view.findViewById(R.id.dialog_btn_sign);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
        //需要先显示再设置大小
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.7 * screenWidth);
        window.setAttributes(params);
    }

    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case ZHECE_OK:
                    dialogLoading.dismiss();
                    button_zhuce.setEnabled(true);
                    dialogshow("注册成功", "注册成功，欢迎使用");
                    break;
                case ZHECE_NO:
                    dialogLoading.dismiss();
                    button_zhuce.setEnabled(true);
                    dialogshow("注册失败", "该用户名可能已存在");
                    break;
                case ZHECE_ERROR:
                    dialogLoading.dismiss();
                    button_zhuce.setEnabled(true);
                    dialogshow("注册失败", "网络连接错误");
                    break;

                case OTHER:
                    dialogLoading.dismiss();
                    button_zhuce.setEnabled(true);
                    dialogshow("注册失败", "出现未知错误");
                    break;

            }

        }
    };

}
